<template>
  <div class="f-pane">
    <el-form :model="project_form" label-width="250px" class="form">
      <el-form-item label="项目名称">
        <el-input v-model="project_form.project_name" />
      </el-form-item>
      <el-form-item label="项目类别">
        <el-radio-group v-model="project_form.project_class" class="ml-4">
          <el-radio v-for="item in projectClass" :label="item" size="small">{{
            item
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="项目类型">
        <el-radio-group v-model="project_form.project_type" class="ml-4">
          <el-radio v-for="item1 in projectType" :label="item1" size="small">{{
            item1
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="专家组">
        <el-radio-group v-model="project_form.project_group" class="ml-4">
          <el-radio
            v-for="item2 in projectGroups"
            :label="item2"
            size="small"
            >{{ item2 }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="项目简介">
        <el-input
          v-model="project_form.project_brief"
          type="textarea"
          placeholder="不超过500字"
        />
      </el-form-item>
      <el-form-item label="项目背景">
        <el-input
          v-model="project_form.project_background"
          type="textarea"
          placeholder="不超过300字"
        />
      </el-form-item>
      <el-form-item label="项目创新点">
        <el-input
          v-model="project_form.project_annotation"
          type="textarea"
          placeholder="不超过300字"
        />
      </el-form-item>
      <el-form-item label="项目预期效果/推广价值">
        <el-input
          v-model="project_form.project_effect"
          type="textarea"
          placeholder="不超过300字"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="addMember">添加项目成员</el-button>
      </el-form-item>
      <el-form
        v-for="members in projectMembers.project_menbers_forms"
        :key="members.key"
        :label="'成员' + members.key"
        :prop="'domains.' + members.key + '.value'"
        class="memberForm"
        label-width="300px"
      >
        <el-form-item :label="'成员' + members.key + '：姓名'">
          <el-input v-model="members.user_fullname" />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="members.user_department"
            placeholder="Select"
            style="width: 115px"
          >
            <el-option
              v-for="item in departments"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="贡献度">
          <el-input-number
            v-model="members.menbers_percentage"
            :step="20"
            min="0"
            max="100"
          />
          %
        </el-form-item>
        <el-form-item label="主要工作内容">
          <el-input v-model="members.members_job" type="textarea" />
        </el-form-item>

        <el-form-item>
          <el-button class="mt-2" @click.prevent="removeMember(members)"
            >删除</el-button
          >
        </el-form-item>
        <el-divider />
      </el-form>
      <el-form-item label="上传项目相关材料">
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action=""
          :headers="{
            Authorization,
          }"
          multiple
          :limit="3"
          name="files"
          :data="{ project_id: project_id }"
          :auto-upload="false"
          :on-change="handleChange"
          :on-remove="handleRemove"
        >
          <el-button type="primary">点击上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">最多可传3个文件</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { onBeforeMount, onMounted, onUpdated, reactive, ref } from "vue";
import { useCookies } from "@vueuse/integrations/useCookies";
import { useStore } from "vuex";
import { message } from "@/composables/util";
import { getToken } from "@/composables/auth";
import {
  getProjectGroups,
  getProjectClass,
  getProjectType,
  save_files,
  submit_project,
  getDepartments,
  cancelProject,
} from "@/api/apiv1";

const cookie = useCookies();
const store = useStore();

const projectGroups = ref([]);
const projectType = ref([]);
const projectClass = ref([]);
const departments = ref([]);

const project_id = ref(0);
const Authorization = getToken();
let fileList = [];
const uploadRef = ref([]);
const uploadFileAction = "/api/v1/save_files";

const init = () => {
  getProjectGroups().then((res) => {
    projectGroups.value = res.data;
  }),
    getProjectClass().then((res) => {
      projectClass.value = res.data;
    }),
    getProjectType().then((res) => {
      projectType.value = res.data;
    }),
    getDepartments().then((res) => {
      departments.value = res.data;
    });
};

onMounted(() => {
  init();
});

const projectMembers = reactive({
  project_menbers_forms: [
    {
      key: 1,
      user_fullname: store.state.user.username,
      user_department: store.state.user.department,
      menbers_percentage: 0,
      members_job: "",
    },
  ],
});

const removeMember = (item) => {
  const index = projectMembers.project_menbers_forms.indexOf(item);
  if (projectMembers.project_menbers_forms.length == 1) {
    message("无法删除，项目至少一个成员", "error");
  } else if (index !== -1) {
    projectMembers.project_menbers_forms.splice(index, 1);
  }
};

const addMember = () => {
  projectMembers.project_menbers_forms.push({
    key: projectMembers.project_menbers_forms.length + 1,
    user_fullname: "",
    user_department: "",
    menbers_percentage: 0,
    members_job: "",
  });
};

// do not use same name with ref
const project_form = reactive({
  project_name: "",
  department: store.state.user.department,
  project_class: projectClass[0],
  project_type: projectType[0],
  project_background: "",
  project_brief: "",
  project_annotation: "",
  project_effect: "",
  project_group: projectGroups[0],
  project_code: "",
  statu: "",
});

// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用,function(file, fileList)
const handleChange = (file, fileListIn) => {
  this.fileList = fileListIn;
};
// 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。function(file, fileList)
const handleRemove = (file, fileListIn) => {
  this.fileList = fileListIn;
};
const onSubmit = () => {
  console.log(project_form);
  console.log(projectMembers.project_menbers_forms);

  submit_project(project_form, projectMembers.project_menbers_forms).then(
    (res) => {
      console.log(res);
      if (res.code == 200) {
        project_id.value = res.data.id;
        const formData = new FormData();
        fileList.forEach((file) => {
          formData.append("files", file.raw);
        });
        if (fileList && fileList.length > 0) {
          save_files(res.data.id, formData)
            .then((res) => {
              console.log(res);
              if (res.code == 200) {
                message("提交成功");
              } else {
                cancelProject(project_id.value);
              }
            })
            .catch((err) => {
              cancelProject(project_id.value);
            });
        } else {
          message("提交成功");
        }
      } else {
        message(res.msg, "error");
      }
    }
  );
};
</script>

<style>
.f-pane {
  @apply flex;
  top: 108px;
}
.memberForm .el-input {
  --el-input-width: 200px;
}
</style>
